package com.vatsalya.bakthi.yoga.services;

import java.io.IOException;

import android.app.Service;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;

public class MusicBackgroundService extends Service {
	    
		MediaPlayer player;
	    
		private static MusicBackgroundService instance = null;
		private static String _currentlyPlayingTrack = null;
		
		public static String currentlyPlayingTrack(){
			return _currentlyPlayingTrack;
		}
		
		public static boolean IsServiceRunning(){
			return (instance != null);
		}
	    
	    public IBinder onBind(Intent intent) {
	        return null;
	    }
	    @Override
	    public void onCreate() {
	        super.onCreate();
	        player = null;
	    }
	    public int onStartCommand(Intent intent, int flags, int startId) {
	    	instance = this;
	    	try {
	    		player = new MediaPlayer();
				player.setVolume(100,100);
				player.reset();
	    		String mantra = intent.getExtras().getString("fileName");
	    		_currentlyPlayingTrack = mantra;
	    		Log.v("Siva", "mantra");
				AssetFileDescriptor fd = getAssets().openFd(mantra);
				player.setDataSource(fd.getFileDescriptor(),fd.getStartOffset(),fd.getLength());
				fd.close();
				player.setLooping(true); // Set looping
				player.prepare();
				player.start();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	        return 1;
	    }

	    public void onStart(Intent intent, int startId) {
	        super.onStart(intent, startId);
	    }
	    public IBinder onUnBind(Intent arg0) {
	        // TO DO Auto-generated method
	        return null;
	    }

	    public void onStop() {
	    	player.stop();
	    	instance = null;
	    }
	    public void onPause() {

	    }
	    @Override
	    public void onDestroy() {
	        player.stop();
	        player.release();
	    }

	    @Override
	    public void onLowMemory() {

	    }

}
